package com.vrv.im.control;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.vrv.im.domain.ProgressBean;
import com.vrv.im.domain.ProjectBean;
import com.vrv.im.domain.RoleBean;
import com.vrv.im.domain.UserBean;
import com.vrv.im.service.AnnexRelatedService;
import com.vrv.im.service.AnnexService;
import com.vrv.im.service.ProgressService;
import com.vrv.im.service.ProjectService;
import com.vrv.im.service.RoleService;
import com.vrv.im.service.UserRoleService;
import com.vrv.im.service.UserService;
import com.vrv.im.util.Constant;
import com.vrv.im.util.Util;
import com.vrv.im.vo.ProgressVo;
import com.vrv.im.vo.ProjectVo;

@Controller
@RequestMapping("/progress")
public class ProgressController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProgressService progressService;
    @Autowired
    private AnnexRelatedService annexRelatedService;
    @Autowired
    private AnnexService annexService;
    @Autowired
    private AnnexRelatedService annexRelationService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("dd/MM/yyyy HH:mm aa"), true));
    }

    @RequestMapping("/goToProgress")
    public ModelAndView gotoPage(@ModelAttribute("voModel") UserBean userBean) {

        if (userBean == null || !StringUtils.hasText(userBean.getOpenId())
                || !StringUtils.hasText(userBean.getToken())) {
            ModelAndView mav = new ModelAndView("userbind/bind");
            mav.addObject("voModel", new UserBean());
            mav.addObject("type", "error");
            mav.addObject("errotMsg", "请传递参数openID，tocken");
            return mav;
        } else {

            userBean = userService.getUserByTokenID(userBean);
            if (null == userBean || !StringUtils.hasText(userBean.getId() + "")) {
                ModelAndView mav = new ModelAndView("userbind/bind");
                mav.addObject("voModel", new UserBean());
                mav.addObject("type", "error");
                mav.addObject("errotMsg", "非法用户！");
                return mav;
            } else {
                List<ProjectVo> list = userRoleService
                        .getBindProjectByUserID(userBean.getId());
                if (list == null || list.size() <= 0) {
                    Map<String, String> error = new HashMap<String, String>();
                    error.put("error", "该用户没有绑定项目");
                    return new ModelAndView("404", error);
                }
                if (list.size() > 1) {
                    List<Long> projectIDList = new ArrayList<Long>();
                    for (ProjectVo v : list) {
                        projectIDList.add(v.getProjectID());
                    }
                    List<ProjectBean> projectList = projectService
                            .getProjectByListID(projectIDList);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("projectList", projectList);
                    return new ModelAndView("progress/select", map);
                }
                long projectID = list.get(0).getProjectID();
                RedirectView v = new RedirectView();
                v.setUrl("goToView.do?projectID=" + projectID);
                return new ModelAndView(v);
            }
        }
    }

    @RequestMapping("/goToView")
    public ModelAndView goToView(@RequestParam("projectID") long projectID) {
        // List<ProgressListVo> progressList = new ArrayList<ProgressListVo>();
        List<ProgressVo> voList = new ArrayList<ProgressVo>();
        ProjectBean projectBean = projectService.getProjectByID(projectID);
        voList = progressService.getProgressByProIDTime(projectID);

        // progressList = progressService.getProgressByProIDTime(projectID);
        // Set<String> progressTimes =
        // progressService.getCreateTimeByProID(projectID);
        // for (String time : progressTimes) {
        // ProgressListVo v = new ProgressListVo();
        // v.setTime(time);
        // List<ProgressVo> list = getProgressVo(projectID, time);
        // v.setList(list);
        // progressList.add(v);
        // }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("voList", voList);
        map.put("project", projectBean);
        return new ModelAndView("progress/view", map);
    }

    @SuppressWarnings("unused")
	private List<ProgressVo> getProgressVo(long projectID, String time) {
        List<ProgressVo> resultList = new ArrayList<ProgressVo>();
        List<ProgressBean> progressList = progressService
                .getProgressByProID(projectID);
        for (ProgressBean b : progressList) {
            String createTime = new SimpleDateFormat("yyyy年MM月dd日").format(b
                    .getCreateTime());
            if (time.equals(createTime)) {
                ProgressVo v = new ProgressVo();
                UserBean ub = userService.getUserByUserID(b.getUserID());
                v.setUserID(ub.getId());
                v.setUserName(ub.getName());
                long roleID = userRoleService.getRoleIDByUserID(b.getUserID(),
                        b.getProjectID());
                RoleBean roleBean = roleService.getRoleNameByRoleID(roleID);
                v.setRoleID(roleBean.getRoleID());
                v.setRoleName(roleBean.getRoleName());
                v.setProgressInfo(b.getProgressInfo());
                List<Long> fileListID = annexRelatedService.getFileID(
                        b.getProgressID(), Constant.ANNEX_TYPE_PROGRESS);
                if (fileListID != null && fileListID.size() > 0) {
                    List<String> fileUrls = annexService
                            .getFileByListID(fileListID);
                    v.setFileUrls(fileUrls);
                }
                resultList.add(v);
            }
        }
        return resultList;
    }

    @RequestMapping("/goToAdd")
    public ModelAndView goToProgress(@RequestParam("projectID") long projectID,
            @ModelAttribute("voModel") UserBean ub) {
        // UserBean ub = (UserBean) session.getAttribute("userBean");
        if (ub == null || !StringUtils.hasText(ub.getOpenId())
                || !StringUtils.hasText(ub.getToken())) {
            ModelAndView mav = new ModelAndView("userbind/bind");
            mav.addObject("voModel", new UserBean());
            mav.addObject("type", "error");
            mav.addObject("errotMsg", "请传递参数openID，tocken");
            return mav;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("projectID", projectID);
        map.put("id", ub.getId());
        map.put("openId", ub.getOpenId());
        map.put("token", ub.getToken());
        return new ModelAndView("progress/add", map);

    }

    @SuppressWarnings("deprecation")
    @RequestMapping(value = "/addProgress", method = RequestMethod.POST)
    public ModelAndView addProgress(HttpServletRequest request,
            @ModelAttribute("voModel") UserBean ub,
            @RequestParam("projectID") long projectID,
            @RequestParam("progressInfo") String progressInfo,
            @RequestParam("file") MultipartFile[] file) {
        if (ub == null || !StringUtils.hasText(ub.getOpenId())
                || !StringUtils.hasText(ub.getToken())) {
            ModelAndView mav = new ModelAndView("userbind/bind");
            mav.addObject("voModel", new UserBean());
            mav.addObject("type", "error");
            mav.addObject("errotMsg", "请传递参数openID，tocken");
            return mav;
        }
        ProgressBean b = new ProgressBean();
        b.setProjectID(projectID);
        b.setUserID(ub.getId());
        b.setProgressInfo(progressInfo);
        b.setCreateTime(new Date());
        long progressID = progressService.addProgress(b);
        if (progressID > 0) {
            String realPath = request.getRealPath("/");
            List<String> fileUrls = new ArrayList<String>();
            for (MultipartFile f : file) {
                try {
                    String path = realPath + "MyFile\\";
                    String fileName = String.valueOf(new Date().getTime())
                            + Util.getFileType(f.getOriginalFilename());
                    File targetFile = new File(path, fileName);
                    f.transferTo(targetFile);
                    fileUrls.add("MyFile/" + fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileUrls != null && fileUrls.size() > 0) {
                List<Long> fileIDs = annexService.addAnnex(fileUrls);
                annexRelationService.addRelation(Constant.ANNEX_TYPE_PROGRESS,
                        b.getProgressID(), fileIDs);
            }
        }
        RedirectView v = new RedirectView();
        v.setUrl("goToView.do");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("projectID", projectID);
        map.put("openId", ub.getOpenId());
        map.put("token", ub.getToken());
        map.put("id", ub.getId());
        return new ModelAndView(v, map);
    }

}
